<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item label="入库日期">
              <j-date
                :show-time="true"
                date-format="YYYY-MM-DD"
                placeholder="请选择开始时间"
                class="query-group-cust"
                v-model="queryParam.entryDateBegin"></j-date>
              <span class="query-group-split-cust"></span>
              <j-date
                :show-time="true"
                date-format="YYYY-MM-DD"
                placeholder="请选择结束时间"
                class="query-group-cust"
                v-model="queryParam.entryDateEnd"></j-date>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('作业入库记录')">导出</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        <span style="float:right;">
          <a-popover title="自定义列" trigger="click" placement="leftBottom">
            <template slot="content">
              <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                <a-row style="width: 400px">
                  <template v-for="(item,index) in defColumns">
                    <template v-if="item.key!=='rowIndex'&& item.dataIndex!=='action'">
                        <a-col :span="12"><a-checkbox :value="item.dataIndex"><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox></a-col>
                    </template>
                  </template>
                </a-row>
              </a-checkbox-group>
            </template>
            <a><a-icon type="setting" />设置</a >
          </a-popover>
        </span>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="inboundRecordItemId"
        :columns="computedColumns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap1"
        @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a @click="handleRevoke(record)" style="color: #ff4d4f;">撤销</a>
        </span>
      </a-table>
    </div>

    <work-inbound-record-modal ref="modalForm" @ok="modalFormOk"></work-inbound-record-modal>
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import WorkInboundRecordModal from './modules/WorkInboundRecordModal'
import { putAction } from '@api/manage'
import dayjs from 'dayjs'

export default {
  name: 'WorkInboundRecordList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    WorkInboundRecordModal
  },
  data() {
    return {
      description: '作业入库记录管理页面',
      queryParam: {
        entryDateBegin: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
        entryDateEnd: dayjs().format('YYYY-MM-DD')
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '入库记录单号',
          align: 'center',
          dataIndex: 'recordNumber'
        },
        {
          title: '计划单号',
          align: 'center',
          dataIndex: 'documentNumber'
        },
        {
          title: '订单编号',
          align: 'center',
          dataIndex: 'orderNumber'
        },
        {
          title: '客户物料编码',
          align: 'center',
          dataIndex: 'customerMaterialCode'
        },
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'materialCode'
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'specificationModel'
        },
        {
          title: '生产日期',
          align: 'center',
          dataIndex: 'productionDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '批次号',
          align: 'center',
          dataIndex: 'batchNumber'
        },
        {
          title: '物料批号',
          align: 'center',
          dataIndex: 'materialBatchNumber'
        },
        {
          title: '储位',
          align: 'center',
          dataIndex: 'storageLocation_dictText'
        },
        {
          title: '入库数量',
          align: 'center',
          dataIndex: 'quantity'
        },
        {
          title: '入库日期',
          align: 'center',
          dataIndex: 'entryDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '保质期（天）',
          align: 'center',
          dataIndex: 'shelfLife'
        },
        {
          title: '操作人',
          align: 'center',
          dataIndex: 'createBy_dictText'
        },
        {
          title: '操作时间',
          align: 'center',
          dataIndex: 'createTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '质检状态',
          align: 'center',
          dataIndex: 'qualityInspectionStatus_dictText'
        },
        {
          title: '检验标准',
          align: 'center',
          dataIndex: 'inspectionStandard'
        },
        {
          title: '抽检数量',
          align: 'center',
          dataIndex: 'samplingQuantity'
        },
        {
          title: '检验结果',
          align: 'center',
          dataIndex: 'inspectionResult'
        },
        {
          title: '检验人',
          align: 'center',
          dataIndex: 'inspector_dictText'
        },
        {
          title: '检验部门',
          align: 'center',
          dataIndex: 'inspectionDeptCode'
        },
        {
          title: '检验日期',
          align: 'center',
          dataIndex: 'inspectionDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 80,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/wms/inbound/work-inbound-record/list',
        exportXlsUrl: '/wms/inbound/work-inbound-record/exportXls',
        revokeUrl: '/wms/inbound/inbound-record/revoke'
      },
      dictOptions: {},
      settingColumns: [],
      superFieldList: []
    }
  },
  created() {
  },
  beforeDestroy() {
    // 组件销毁前保存列设置到sessionStorage
    sessionStorage.setItem('workInboundRecordListColumns', JSON.stringify(this.settingColumns))
  },
  mounted() {
    // 组件挂载后恢复列设置
    const savedColumns = JSON.parse(sessionStorage.getItem('workInboundRecordListColumns'))
    if (savedColumns && savedColumns.length > 0) {
      this.settingColumns = savedColumns
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    // 添加计算属性，根据settingColumns过滤显示的列
    computedColumns() {
      // 获取所有列的数据索引
      const allColumns = this.columns.map(col => col.dataIndex)
      // 如果设置了自定义列，则过滤显示
      if (this.settingColumns && this.settingColumns.length > 0) {
        return this.columns.filter(col => 
          this.settingColumns.includes(col.dataIndex) || 
          !col.dataIndex || // 保留没有dataIndex的列（如序号列）
          col.dataIndex === 'action' // 保留操作列
        )
      }
      // 默认显示所有列
      return this.columns
    }
  },
  methods: {
    onColSettingsChange(checkedValues) {
      // 存储到localStorage
      sessionStorage.setItem('workInboundRecordListColumns', JSON.stringify(checkedValues))
      localStorage.setItem('workInboundRecordListColumns', JSON.stringify(checkedValues))
      this.settingColumns = checkedValues
    },
    initDictConfig() {
    },
    handleRevoke(record) {
      this.$confirm({
        title: '确定撤回此记录吗？',
        content: `该操作将撤回单号为 ${record.recordNumber} 的入库记录，是否继续？`,
        onOk: () => {
          const url = `${this.url.revokeUrl}/${record.id}`
          putAction(url).then(res => {
            if (res.success) {
              this.$message.success('撤销成功')
              this.searchQuery()
            } else {
              this.$message.error(res.message || '撤销失败')
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>